<!--
 * @Descripttion:
 * @version:
 * @Author: 韩应波
 * @Date: 2021-03-03 15:23:13
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-03-15 09:42:50
-->
<template>
  <div class="application" v-loading="listLoading">
    <div
      v-for="(item, index) in groupList"
      :key="index"
      :class="['group', item.edit ? 'active' : '']"
    >
      <div class="title">
        <div v-if="item.edit">
          分组名称：
          <el-input
            v-model="item.name"
            class="name-input"
            placeholder="请输入分组名称"
            maxlength="5"
          />
        </div>
        <h3 v-else>{{ item.name }}</h3>
        <div class="handle" v-if="!editingMode">
          <auth-button
            @click="moveItem(index, -1)"
            name="上移"
            circle
            v-if="index > 0"
            isText
          >
            <i class="el-icon-upload2"></i>
          </auth-button>
          <auth-button
            @click="moveItem(index, 1)"
            name="下移"
            circle
            v-if="index < groupList.length - 1"
            isText
          >
            <i class="el-icon-download"></i>
          </auth-button>
          <auth-button name="编辑" @click="item.edit = true" isText />
          <auth-button
            name="删除"
            @click="deleteGroup(item)"
            :elPopconfirmProps="{
              title: '警告，确定要删除该分组吗？删除后将无法恢复',
              'confirm-button-type': 'danger'
            }"
            isText
          />
        </div>
      </div>

      <!-- 应用列表 -->
      <application v-model="item.applicationList" :edit="item.edit" />

      <div v-if="item.edit">
        序号：
        <Sort v-model="item.sort" :max="99" />
        <div class="edit">
          <el-button @click="cancel(item)" v-if="!btnLoading">取消</el-button>
          <el-button
            type="primary"
            @click="submit(item, index)"
            :loading="btnLoading"
          >
            提交
          </el-button>
        </div>
      </div>
    </div>
    <p v-if="groupList.length == 0 && !listLoading" class="no-data">
      无分组数据
    </p>
    <auth-button name="添加分组" v-if="!editingMode" @click="addGroup()" />
  </div>
</template>
<script>
import application from './application'

export default {
  name: 'groups',
  props: ['areaCode'],
  components: { application },
  data () {
    return {
      listLoading: true,
      btnLoading: false,
      groupList: []
    }
  },
  watch: {
    areaCode (n) {
      this.getList()
    }
  },
  computed: {
    // 编辑模式
    editingMode () {
      return this.groupList.filter(_ => _.edit).length > 0
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 移动项目
    moveItem (index, direction) {
      let curr = this.groupList[index],
        next = this.groupList[index + direction]
      this.listLoading = true
      Promise.all([
        this.updateSort(curr, next.sort),
        this.updateSort(next, curr.sort)
      ])
        .catch(_ => {
          this.$swal.error('修改失败')
        })
        .finally(_ => {
          this.getList()
          this.listLoading = false
        })
    },
    // 改变分组顺序
    updateSort (data, sort) {
      return this.$POST('one-travel-api/application-group/insertOrUpdate', {
        ...data,
        sort
      })
    },
    // 提交数据
    submit (item, index) {
      if (this.verifyForm(item, index)) {
        this.btnLoading = true
        this.$POST('one-travel-api/application-group/insertOrUpdate', {
          ...item,
          areaCode: this.areaCode
        })
          .then(res => {
            if (res.errorCode == '00000') {
              this.$swal.success('操作成功')
              item.edit = false
              this.getList()
            } else {
              this.$swal.error(res.message)
            }
          })
          .finally(_ => {
            this.btnLoading = false
          })
      }
    },
    // 删除分组
    deleteGroup (item) {
      this.$POST('one-travel-api/application-group/delete', {
        id: item.id
      })
        .then(res => {
          if (res.errorCode == '00000') {
            this.$swal.success('操作成功')
            this.getList()
          } else {
            this.$swal.error(res.message)
          }
        })
        .finally(_ => {
          this.btnLoading = false
        })
    },
    // 获取数据
    getList () {
      this.listLoading = true
      this.$POST('one-travel-api/application-group/queryForList', {
        areaCode: this.areaCode
      })
        .then(res => {
          this.groupList = []
          if (res.errorCode == '00000') {
            this.groupList = res.data.map(item => {
              return {
                ...item,
                edit: false
              }
            })
          } else {
            this.$swal.error(res.message)
          }
        })
        .finally(_ => {
          this.listLoading = false
          this.btnLoading = false
        })
    },
    // 添加分组
    addGroup () {
      if (this.groupList.length >= 10) {
        this.$swal.error('每个地区应用最多只能添加10组')
        return
      }
      let sort = 1
      if (this.groupList.length > 0) {
        sort = this.groupList[this.groupList.length - 1].sort + 1
      }
      this.groupList.push({
        name: '',
        applicationList: [],
        sort,
        edit: true
      })
    },
    // 取消按钮
    cancel (item) {
      if (item.id) {
        this.getList() // 如果是修改已有的数据点了取消，直接重新获取数据
      } else {
        if (item.name != '' || item.applicationList.length > 0) {
          this.$confirm('您已输入内容，确定移除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '我再想想',
            type: 'warning'
          }).then(() => {
            this.groupList.pop()
          })
        } else {
          this.groupList.pop() // 没有输入数据，直接移除
        }
      }
    },
    // 验证表单
    verifyForm (item, index) {
      if (item.name == '') {
        this.$swal.error('请输入分组名称')
        return false
      }
      if (item.applicationList.length == 0) {
        this.$swal.error('至少添加一个应用')
        return false
      }
      if (item.sort == '') {
        this.$swal.error('请输入序号')
        return false
      }
      let g = this.groupList
      for (let i = 0; i < g.length; i++) {
        if (i != index && item.sort == g[i].sort) {
          this.$swal.error('序号已存在')
          return false
        }
      }
      return true
    }
  }
}
</script>
<style lang="scss" scoped>
$--color-primary: #1890ff;
.application {
  min-height: 300px;
  .group {
    border-bottom: 1px solid #eee;
    margin-bottom: 10px;
    padding: 10px;
    &.active {
      background-color: #f6f6f6;
    }
    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #f6f6f6;
      height: 56px;
      h3 {
        line-height: 1;
        padding-left: 10px;
        border-left: 3px solid $--color-primary;
        margin: 0;
      }
      .name-input {
        width: 400px;
      }
    }
    .edit {
      width: 100%;
      padding-top: 20px;
      text-align: center;
    }
  }
  .no-data {
    margin-top: 0;
    color: #666;
    line-height: 100px;
    text-align: center;
    background-color: #f6f6f6;
  }
}
</style>
